package com.free.bsf.core.config;

import com.free.bsf.core.filter.CORSFilter;
import com.free.bsf.core.filter.WebContextFilter;
import com.free.bsf.core.filter.WebContextInterceptor;
import com.free.bsf.core.serialize.JsonSerializer;
import com.free.bsf.core.util.ContextUtils;
import com.free.bsf.core.util.LogUtils;
import lombok.val;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author: chejiangyi
 * @version: 2019-07-01 19:07
 **/
@Configuration
@ConditionalOnWebApplication
public class WebConfiguration  implements WebMvcConfigurer {

    /**
     * 跨域策略
     * @return
     */
    @Bean
    @ConditionalOnProperty(name = "bsf.web.cors3.enabled", havingValue = "true")
    public CORSFilter corsFilter3() {
        return new CORSFilter();
    }

    @Bean
    @ConditionalOnProperty(name = "bsf.web.serialize3.enabled", havingValue = "true")
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
        return new MappingJackson2HttpMessageConverter(JsonSerializer.getDefaultObjectMapper());
    }

    @Bean
    @ConditionalOnProperty(name = "bsf.web.context.enabled", havingValue = "true",matchIfMissing = true)
    public FilterRegistrationBean webContextFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        //优先注入
        filterRegistrationBean.setOrder(-1);
        filterRegistrationBean.setFilter(new WebContextFilter());
        filterRegistrationBean.setName("webContextFilter");
        filterRegistrationBean.addUrlPatterns("/*");
        LogUtils.info(WebConfiguration.class,CoreProperties.Project,"web请求上下文过滤器注册成功");
        return filterRegistrationBean;
    }

    @Bean
    @ConditionalOnProperty(name = "bsf.web.context.enabled", havingValue = "true",matchIfMissing = true)
    public WebContextInterceptor webContextInterceptor() {
        return new WebContextInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        val interceptor = ContextUtils.getBean(WebContextInterceptor.class,false);
        if(interceptor!=null) {
            registry.addInterceptor(interceptor);
        }
    }
}
